// 系统通知 - 列表
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { parse } from 'qs';
import { Card, Form, Row, Col, Button, Input, Table, DatePicker, Select, Modal, message } from 'antd';
import {
  SearchOutlined,
  DeleteOutlined,
  ReadOutlined,
} from '@ant-design/icons';
import * as listApi from '~/apis/dashboard/dashboardApi';
import './index.local.sass';
import { getColumns, timestampToTime } from './pageConfig';

const { Option } = Select;

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const FormItem = Form.Item;
const { confirm } = Modal;
const { RangePicker } = DatePicker;
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const showTotal = (total: number) => `Total: ${total}`;

const MessagesList = observer(() => {
  const querryParams = parse(location.search, { ignoreQueryPrefix: true });

  const state = useLocalStore(() => ({
    userId: querryParams.id || '',
    loading: false,
    tableList: {
      data: [],
      pageNo: 1,
      pageSize: 10,
      totalCount: 0,
      totalPage: 0,
    },
    getData: {},
    visible: false,
    replyVisible: false,
    message: {
      subject: '',
      content: '',
      createTime: 0,
      sendName: '',
    },
    ids: '',
  }));

  const [form] = Form.useForm();

  const doQuery = (curPage: number = 1) => {
    state.tableList.pageNo = curPage;

    const { pageNo, pageSize } = state.tableList;

    const params = {
      pageNum: pageNo,
      pageSize,
      ...state.getData,
    };

    state.loading = true;

    listApi.getNotificationList(params).then((res) => {
      state.tableList = {
        ...state.tableList,
        data: res.data,
        totalCount: res.pageInfo.total,
        totalPage: res.pageInfo.totalPages,
      };
    }).finally(() => {
      state.loading = false;
    });
  };

  const onSearch = (values: any) => {
    const time = values.time;
    if (time && time !== null) {
      if (time[0] !== null) {
        values.startTime = new Date(time[0]._d).getTime();
      }
      if (time[1] !== null) {
        values.endTime = new Date(time[1]._d).getTime();
      }
    }
    values.time = [];
    state.getData = values;

    doQuery(1);
  };

  const onReset = () => {
    form.resetFields();

    onSearch({});
  };

  // 查看
  const showMessages = (id: string) => {
    state.visible = true;
    // form.resetFields(); // 清空modal弹框值
    listApi.getMessages(id).then((res: any) => {
      state.message = res.data;
      doQuery(1);
    });
  };

  // 删除
  const deleteMessages = (ids: string) => {
    confirm({
      title: 'Do you Want to delete this messages?',
      onOk() {
        listApi.deleteMessages(ids).then(() => {
          message.success('delete success');
          doQuery(1);
        });
      },
    });
  };

  // 标记已读
  const readMark = (ids: string) => {
    listApi.readMark({ ids }).then(() => {
      message.success('success');
      doQuery(1);
    });
  };

  const columns = getColumns({ showMessages, deleteMessages });

  const {
    loading,
    tableList: { pageNo, totalCount, pageSize, data },
  } = state;

  const tableOption: any = {
    loading,
    columns,
    pagination: {
      current: pageNo,
      total: totalCount,
      pageSize,
      size: 'small',
      showQuickJumper: true,
      showTotal,
      onChange: (curPage: number) => {
        doQuery(curPage);
      },
    },
    dataSource: data || [],
    rowKey: 'id',
    size: 'small',
  };

  const rowSelection = {
    onChange: (selectedRowKeys: any) => {
      let result: any = '';
      selectedRowKeys.forEach((element: any, index: any) => {
        if (index === 0) {
          result = `${element as string}`;
        } else {
          result = `${result as string},${element as string}`;
        }
      });
      state.ids = result;
    },
  };

  const handleCancel = () => {
    state.visible = false;
  };

  React.useEffect(() => {
    doQuery(1);
  }, []);

  return (
    <div>
      <Card {...cardConfig} className='search-card'>
        <Modal
          title='System Notification'
          visible={state.visible}
          onCancel={handleCancel}
          footer={[
            <Button key="back" onClick={handleCancel}>
              Close
            </Button>,
          ]}
        >
          <div style={{ height: 250 }} >
            <p style={{ fontSize: '20px', fontFamily: 'Arial Bold' }}>
              {state.message.subject}
            </p>
            <p style={{ marginBottom: '20px', marginTop: '20px' }}>
              <span>{timestampToTime(state.message.createTime)}&nbsp; &nbsp; &nbsp; &nbsp;{state.message.sendName}</span>
            </p>
            <p>
              {state.message.content}
            </p>
          </div>
        </Modal>
        <Form form={form} onFinish={onSearch}>
          <Row>
            <Col span={4}>
              <FormItem name='time' {...formItemLayout}>
                <RangePicker
                  format='YYYY-MM-DD'
                  placeholder={['Start Time', 'End Time']}
                />
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem name='readStatus' shouldUpdate={true} {...formItemLayout}>
                <Select placeholder='Status' allowClear >
                  <Option value='1'>Unread</Option>
                  <Option value='2'>read</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem name='sendType' {...formItemLayout}>
                <Select placeholder='Transceiver' allowClear >
                  <Option value='1'>Accept</Option>
                  <Option value='2'>Send</Option>
                </Select>
              </FormItem>
            </Col>
            <Col span={4}>
              <FormItem name='searchKey' {...formItemLayout}>
                <Input
                  allowClear={true}
                  onPressEnter={onSearch}
                  prefix={<SearchOutlined style={{ color: '#A9B8CF' }} />}
                />
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout}>
                <Button type='primary' htmlType='submit' className='mr-2'>
                  Search
                </Button>

                <Button className='mr-2' onClick={onReset}>
                  Reset
                </Button>
              </FormItem>
            </Col>
          </Row>

        </Form>
      </Card>
      <Card {...cardConfig} className='card'>
        <div className='mb-4'>
          <Button
            className='mr-2'
            icon={<DeleteOutlined />}
            onClick={() => deleteMessages(state.ids)}
          >
            Delete in batches
          </Button>
          <Button
            className='mr-2'
            icon={<ReadOutlined />}
            onClick={() => readMark(state.ids)}
            style={{ width: 190 }}
          >
            Read
          </Button>
        </div>

        <Table
          rowSelection={{
            type: 'checkbox',
            ...rowSelection,
          }}
          {...tableOption}
        />
      </Card>
    </div>
  );
});

export default MessagesList;
